import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:panda/base/Constant.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:webview_flutter/webview_flutter.dart';
// import 'dart:async';

// import 'package:webview_flutter/webview_flutter.dart';

class KeFuTalkPage extends StatefulWidget {
  String url;
  KeFuTalkPage({Key key, this.url}) : super(key: key);
  @override
  _KeFuTalkPageState createState() => _KeFuTalkPageState(url);
}

class _KeFuTalkPageState extends State<KeFuTalkPage> {
  String url;
  _KeFuTalkPageState(this.url);
  WebViewController _controller;
  FlutterWebviewPlugin plugin = new FlutterWebviewPlugin();
  @override
  Widget build(BuildContext context) {
    // TODO: im,plement build
    return 
   
    WebviewScaffold(
            url: url,
            appBar: AppBar(
                backgroundColor: mainColor,
                title: Text('在线客服'),
                centerTitle: true,
                actions: <Widget>[
                  // new IconButton(
                  //     icon: new Icon(Icons.arrow_left),
                  //     onPressed: () {
                  //       _controller.goBack();
                  //     }),
                  new IconButton(
                      icon: new Icon(Icons.home),
                      onPressed: () {
                      })
                ]),
          );
  }
  // @override
  // Widget build(BuildContext context) {
  //   return ;
  // }

  @override
  void initState() {
    super.initState();
    print(url);
    plugin.onUrlChanged.listen((String value) {

      if (value.startsWith('alipays://') || value.startsWith('alipay://')) {
        //   print('blocking navigation to $request}');
        _openApp(value);
        // 
        setState(() {
          // plugin.goBack();
          plugin.stopLoading();
          plugin.reload();
        });
      }
      if (value.startsWith('weixin://')) {
        //   print('blocking navigation to $request}');
        _openApp(value);
        setState(() {
          plugin.goBack();
        });
      }
    });
  }

  void _openApp(openurl) async {
    // Android
    print("open app");
    final url = 'vnd.' + openurl;
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      //  Ios
      final url = openurl;
      if (await canLaunch(url)) {
        await launch(url);
      } else {
        Fluttertoast.showToast(msg: "打开失败");
        // throw 'Could not launch $url';
      }
    }
  }

  void dispose() {
    super.dispose();
  }
}
